package com.dispacher.util;

import java.lang.reflect.Field;
import java.util.List;

import com.dispacher.context.ContextHolder;

public class JsonUtil {
	public static String parseToJson(Object o) {
		if (o instanceof List) {
			return parseListToJson((List<Object>) o);
		}
		StringBuilder result = new StringBuilder();
		Field[] fields = o.getClass().getDeclaredFields();
		result.append("{");
		for (Field field : fields) {
			try {
				field.setAccessible(true);
				result.append("\"");
				result.append(field.getName());
				result.append("\" : \"");
				result.append(field.get(o));
				result.append("\",");
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		result.deleteCharAt(result.lastIndexOf(","));
		result.append("}");
		return result.toString();
	}

	public static String parseListToJson(List<Object> list) {
		if (list.size() == 0) {
			return "[]";
		}
		StringBuilder result = new StringBuilder();
		result.append("[");
		for (Object o : list) {
			result.append(parseToJson(o));
			result.append(",");
		}
		result.deleteCharAt(result.lastIndexOf(","));
		result.append("]");
		return result.toString();
	}
}
